import com.mit.web.business.proxy.DesignProxy;
import com.mit.web.business.proxy.ManufactureProxy;
import com.mit.web.business.remote.IInvokeResponder;
import com.mit.web.config.Constants;
import com.mit.web.config.SizeGroupConfig;
import com.mit.web.event.PopWinCloseEvent;
import com.mit.web.util.DataFormatUtil;
import com.mit.web.util.FlexUtil;
import com.mit.web.view.component.monitor.IProgressMonitor;
import com.mit.web.view.component.text.NumberTextInput;
import com.mit.web.vo.design.StyleVO;
import com.mit.web.vo.maintenance.ProductColorVO;
import com.mit.web.vo.manufacture.MOItemVO;
import com.mit.web.vo.manufacture.MOVO;

import flash.events.Event;
import flash.events.FocusEvent;
import flash.events.MouseEvent;

import flexlib.scheduling.util.DateUtil;

import mx.collections.ArrayCollection;
import mx.controls.dataGridClasses.DataGridColumn;
import mx.core.ClassFactory;
import mx.events.FlexEvent;
import mx.logging.ILogger;
import mx.rpc.events.ResultEvent;

import spark.components.ComboBox;
import spark.components.NumericStepper;
import spark.events.IndexChangeEvent;

[Bindable] private var _order:MOVO
private var _proxy:ManufactureProxy = ManufactureProxy.getInstance();

private var _pm:IProgressMonitor;
private var _logger:ILogger;

private function creationHandler(event:FlexEvent):void{
	_order = new MOVO();
	_order.creationDate = new Date();
}

private function buildStyleComboBox(event:IndexChangeEvent):void
{
	if(lst_year.selectedIndex > -1 && lst_season.selectedIndex > -1){
		//根据year, season取回已经发布的款式记录
		var designProxy:DesignProxy = DesignProxy.getInstance();
		var rsp:IInvokeResponder = designProxy.getApprovedStyles(lst_year.selectedItem as int, lst_season.selectedId);
		rsp.addResultListener(retrieveStyleHandler);
		rsp.addFaultListener(exceptionHandler);
	}	

}

private function  retrieveStyleHandler(event:ResultEvent):void{
	var lst:ArrayCollection = event.result as ArrayCollection;
	lst_style.dataProvider = lst;
	
}



private function styleSelectedHandler(event:IndexChangeEvent):void{
	var styleBox:ComboBox = event.currentTarget as ComboBox;
	var style:StyleVO = styleBox.selectedItem as StyleVO;
	_order.itemList = new ArrayCollection();	
	if(style){
		//为item赋值
		var colors:ArrayCollection = style.colors;
		for each(var c:ProductColorVO in colors){
			var i:MOItemVO = new MOItemVO();
			i.colorId = c.id;
			i.colorName = c.codeAndName;
			_order.itemList.addItem(i);
		}
		dg.validateNow();
		//动态增加尺码列
		var sizeFields:ArrayCollection = style.sizeFields;
		var sizeNames:ArrayCollection = SizeGroupConfig.getInstance().getSelectedSizes(style.sizeGroup, sizeFields);
		for(var j:int = 0; j < sizeFields.length; j++){
			var dgc:DataGridColumn = new DataGridColumn();
			dgc.headerText = sizeNames[j];
			dgc.dataField = sizeFields[j];
			dgc.setStyle("headerStyleName","datagridHeader");
			dgc.setStyle("textAlign","right");
			dgc.itemEditor = new ClassFactory(com.mit.web.view.component.text.NumberTextInput);
			var cols:Array = dg.columns;
			cols.push(dgc);
			dg.columns = cols;
		}
	}else{
		//删除尺码组，还原列表
		var cols:Array = dg.columns;
		for(var x:int = 1; x < cols.length; x++)
			cols.pop();
		dg.columns = cols;
	}
	//更新列表
	dg.validateNow();
}

private function doConfirm():void{
	//Validation
	if(validate() == false){
		return ;
	}
	
	//assemble vo
	assembleVO();
	_order.state = Constants.MO_STATE_APPR;
	
	var resp:IInvokeResponder = _proxy.saveMO(_order);
	resp.addResultListener(newMOSavedHandler);
	resp.addFaultListener(exceptionHandler);
}

private function doSave(event:MouseEvent):void{
	//Validation
	if(validate() == false){
		event.preventDefault();
		return ;
	}
	
	//assemble vo
	assembleVO();
	_order.state = Constants.MO_STATE_NEW;
	
	var resp:IInvokeResponder = _proxy.saveMO(_order);
	resp.addResultListener(newMOSavedHandler);
	resp.addFaultListener(exceptionHandler);	
}

private function newMOSavedHandler(event:ResultEvent):void{
	var mo:MOVO = event.result as MOVO;
	var e:PopWinCloseEvent = new PopWinCloseEvent(PopWinCloseEvent.CREATED);
	e.vo = mo;
	e.msg = ResourceManager.getInstance()
		.getString(Constants.BUNDLE_COMMON,"info.common.saved",[mo.code]);
	this.dispatchEvent(e);
	closeWindow(this);
}

private function validate():Boolean{

	if(lst_style.selectedIndex < 0){
		showRequiredErrorTip(lst_style);
		return false;
	}
	if(cmb_factory.selectedId < 1){
		showRequiredErrorTip(cmb_factory);
		return false;
	}
	if(txt_fee.number <= 0){
		showRequiredErrorTip(txt_fee);
		return false;
	}
	return true;
}

private function assembleVO():void{
	var selectedStyle:StyleVO = lst_style.selectedItem as StyleVO;
	_order.styleId = selectedStyle.id;
	_order.styleCode = selectedStyle.code;
	_order.productTypeId = selectedStyle.prodTypeId;
	_order.productTypeName = selectedStyle.prodTypeName;
	_order.productName = selectedStyle.name;
	_order.sizeGroup = selectedStyle.sizeGroup;
	_order.estimatedFee = selectedStyle.estimatedFee;
	_order.img = selectedStyle.img;
	_order.creationDate = dat_creation.selectedDate;
	_order.deliverDate = DateUtil.addTime(DateUtil.copyDate(dat_creation.selectedDate), DateUtil.DAY_IN_MILLISECONDS * ns_deliver.value);
	_order.estimatedFee = selectedStyle.estimatedFee;
	_order.actualFee = txt_fee.number;
	_order.wholesalePrice = txt_wsPrice.number;
	_order.retailPrice = txt_retailPrice.number;
	_order.factoryId = cmb_factory.selectedId;
	_order.factoryName = cmb_factory.selectedItem.label;
	_order.remarks = txt_rmk.text;
	_order.sizeFields = selectedStyle.sizeFields;

	//sumup total qty in the item list;
	var totalQty:int = 0;
	var sizeFields:ArrayCollection = selectedStyle.sizeFields;
	for each(var item:MOItemVO in _order.itemList){
		for each(var size:String in sizeFields){
			totalQty += item[size];
		}
	}
	_order.orderQty = totalQty;
}

